package com.arpa.oms.controller;

import cn.hutool.core.util.StrUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.oms.domain.dto.OmsSaleReturnDTO;
import com.arpa.oms.domain.entity.OmsSaleReturn;
import com.arpa.oms.domain.enums.OrderStatusEnum;
import com.arpa.oms.domain.vo.OmsSaleReturnVO;
import com.arpa.oms.service.IOmsSaleReturnService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * OMS销售退货单 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-11-17
 */
@Api(tags = "OMS销售退货单")
@RestController
@RequestMapping(value="/omsSaleReturn", produces = "application/json;charset=UTF-8")
@Log4j2(topic = "business")
public class OmsSaleReturnController {

   @Autowired
   private IOmsSaleReturnService  iOmsSaleReturnService;

    /**
     * 获取 OMS销售退货单 列表
     *
     * @param omsSaleReturnDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 OMS销售退货单 列表", notes = "获取 OMS销售退货单 列表")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsSaleReturnVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(OmsSaleReturnDTO omsSaleReturnDTO,HttpServletRequest request) {
        try {

            omsSaleReturnDTO.setGroupCode(UserUtil.getBranchCode());
            omsSaleReturnDTO.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            omsSaleReturnDTO.setWarehouseCodes(UserUtil.getShipmentAuthorizeWarehouseCodes());

            OmsSaleReturnVO omsSaleReturnVOSum = iOmsSaleReturnService.queryListSum(omsSaleReturnDTO);
            List<OmsSaleReturnVO> omsSaleReturnVOList = iOmsSaleReturnService.queryList(omsSaleReturnDTO);

            Page returnPage = new Page(omsSaleReturnDTO.getPageNum(),omsSaleReturnDTO.getPageSize());
            returnPage.setRecords(omsSaleReturnVOList);
            returnPage.setTotal(omsSaleReturnVOSum.getTotal());
            returnPage.setSumObject(omsSaleReturnVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加/修改 OMS销售退货单
     *
     * @param entity OmsSaleReturn
     * @param request
     * @return
     */
    @ApiOperation(value = "添加 OMS销售退货单 ", notes = "添加 OMS销售退货单 ")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@Validated(OmsSaleReturn.Save.class) @RequestBody OmsSaleReturn entity, HttpServletRequest request) {
        try {
            entity.setShipmentCode(UserUtil.getShipmentCompanyCode());
            entity.setShipmentName(UserUtil.getShipmentCompanyName());

            iOmsSaleReturnService.localSave(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
    * 获取OMS销售退货单详情
    *
    * @param code
    * @param request
    * @return
    */
    @ApiOperation(value = "获取OMS销售退货单详情", notes = "获取OMS销售退货单详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "code", value = "OMS销售退货单code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsSaleReturn.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result omsSaleReturn(@PathVariable String code, HttpServletRequest request) {
        try {
            OmsSaleReturnVO vo = iOmsSaleReturnService.getByCode(code);

            return Result.ok().data(vo);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 修改OMS销售退货单
     *
     * @param entity OMS销售退货单
     * @param request
     * @return
     */
    @ApiOperation(value = "修改OMS销售退货单", notes = "修改OMS销售退货单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(@Validated(OmsSaleReturn.Update.class)@RequestBody OmsSaleReturn entity,HttpServletRequest request) {
        if(StringUtils.isBlank(entity.getCode())){
            return Result.error("单号不能为空");
        }
        entity.setShipmentCode(UserUtil.getShipmentCompanyCode());
        entity.setShipmentName(UserUtil.getShipmentCompanyName());
        int updateNum = iOmsSaleReturnService.updateByCode(entity);
        if(updateNum == 0){
            return Result.error("没有更新数据！单号:"+entity.getCode());
        }else{
            return Result.ok("修改成功,更新"+updateNum+"条数据！");
        }
    }

    /**
     * 删除 OMS销售退货单
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 OMS销售退货单 ", notes = "删除 OMS销售退货单 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
        @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
        @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
        @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iOmsSaleReturnService.remove(new QueryWrapper<OmsSaleReturn>().lambda().in(OmsSaleReturn::getCode,codes));
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 作废 OMS销售退货单
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "作废 OMS销售退货单 ", notes = "作废 OMS销售退货单 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "/annul")
    public Result annul(@RequestParam String code, HttpServletRequest request) {
        try {
            Result result = iOmsSaleReturnService.annul(code);

            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 提交 OMS销售退货单
     *
     * @param entity OMS销售退货单
     * @param request
     * @return
     */
    @ApiOperation(value = "提交 OMS销售退货单", notes = "提交 OMS销售退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/submit")
    public Result submit(@Validated(OmsSaleReturn.Save.class)@RequestBody OmsSaleReturn entity, HttpServletRequest request) {
        entity.setShipmentCode(UserUtil.getShipmentCompanyCode());
        entity.setShipmentName(UserUtil.getShipmentCompanyName());

        iOmsSaleReturnService.submit(entity);

        return Result.ok("提交成功");
    }


    /**
     * 审核销售退货单
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "审核 销售退货单", notes = "审核 销售退货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping(value = "/audit")
    public Result audit(@RequestBody OmsSaleReturn entity, HttpServletRequest request) {
        if(StrUtil.isBlank(entity.getCode())){
            return Result.error("单号不能为空");
        }

        iOmsSaleReturnService.audit(entity);

        return Result.ok(entity.getCode() + "审核成功!");
    }


    /**
     * 获取 OMS销售退货单 审核列表
     *
     * @param omsSaleReturnDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 OMS销售退货单 审核列表", notes = "获取 OMS销售退货单 审核列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OmsSaleReturnVO.class))
    @NeedLogin
    @GetMapping("/auditList")
    public Result auditList(OmsSaleReturnDTO omsSaleReturnDTO,HttpServletRequest request) {
        try {

            omsSaleReturnDTO.setGroupCode(UserUtil.getBranchCode());
            omsSaleReturnDTO.setShipmentCode(UserUtil.getLoginWarehouseCodeOrShipmentCode());
            omsSaleReturnDTO.setWarehouseCodes(UserUtil.getShipmentAuthorizeWarehouseCodes());

            // 前端传的审核状态为空的话，则只查询“待审核”、“审核不通过”、“审核通过”的数据
            if (StrUtil.isBlank(omsSaleReturnDTO.getAuditStatus())) {
                List<String> auditStatus = Arrays.asList(OrderStatusEnum.PENDING.getValue(), OrderStatusEnum.NO_PASS.getValue(), OrderStatusEnum.PASS.getValue());
                String auditStatusStr = auditStatus.stream().map(c -> StrUtil.wrap(c, "'")).collect(Collectors.joining(","));
                omsSaleReturnDTO.setAuditStatus(auditStatusStr);
            }

            OmsSaleReturnVO omsSaleReturnVOSum = iOmsSaleReturnService.queryListSum(omsSaleReturnDTO);
            List<OmsSaleReturnVO> omsSaleReturnVOList = iOmsSaleReturnService.queryList(omsSaleReturnDTO);

            Page returnPage = new Page(omsSaleReturnDTO.getPageNum(),omsSaleReturnDTO.getPageSize());
            returnPage.setRecords(omsSaleReturnVOList);
            returnPage.setTotal(omsSaleReturnVOSum.getTotal());
            returnPage.setSumObject(omsSaleReturnVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE,e);
            return Result.error(e.getMessage());
        }
    }
}
